package com.jyxd.web.service.assessment.basic;

import com.jyxd.web.dao.basic.BodyTemperatureDao;
import com.jyxd.web.data.basic.BodyTemperature;
import com.jyxd.web.data.basic.InOutAmount;
import com.jyxd.web.data.dto.ExtBodyTemplate;
import com.jyxd.web.data.dto.TemperatureMomentDTO;
import com.jyxd.web.service.assessment.TemperatureDataService;
import com.jyxd.web.service.assessment.TemperatureReportService;
import com.jyxd.web.util.SliceUpDateUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class BodyTemperatureService {

    @Autowired
    private BodyTemperatureDao bodyTemperatureDao;

    @Autowired
    private TemperatureReportService temperatureReportService;

    @Autowired
    private VitalSignService vitalSignService;

    @Autowired
    private VitalSignMergeService vitalSignMergeService;

    @Autowired
    private TemperatureDataService temperatureDataService;

    @Autowired
    private InOutAmountService inOutAmountService;

    public boolean insert(BodyTemperature bodyTemperature){
        return bodyTemperatureDao.insert(bodyTemperature);
    }

    public boolean update(BodyTemperature bodyTemperature){
        return bodyTemperatureDao.update(bodyTemperature);
    }

    public BodyTemperature queryData(String id){
        return bodyTemperatureDao.queryData(id);
    }

    public List<BodyTemperature> queryList(Map<String,Object> map){
        return bodyTemperatureDao.queryList(map);
    }



    public int queryNum(Map<String,Object> map){return bodyTemperatureDao.queryNum(map);}

    /**
     * 根据时间查询在科病人的体温图数据
     * @param map
     * @return
     */
    public List<Map<String,Object>> getListByTime(Map<String,Object> map){
        return bodyTemperatureDao.getListByTime(map);
    }

    /**
     * 根据周与病人id查询在科病人的体温图数据
     * @param map
     * @return
     */
    public List<ExtBodyTemplate> getListByWeekAnusTemplate(Map<String,Object> map){
        List<ExtBodyTemplate> list=  bodyTemperatureDao.getListByWeekAnusTemplate(map);
        List<ExtBodyTemplate> newList=new LinkedList<ExtBodyTemplate>();
        getNewList(newList,list,map);
        return newList;
    }

    public void  getNewList(List<ExtBodyTemplate> newList, List<ExtBodyTemplate> list, Map<String,Object> map){

        LinkedHashMap<String, LinkedList<ExtBodyTemplate> > hashMap=new LinkedHashMap<String,LinkedList<ExtBodyTemplate>>();
        LinkedHashMap<String,Integer> dataTimeMap=new LinkedHashMap<String,Integer>();
        String bengin= map.get("startTime").toString();
        String end=map.get("endTime").toString();
        List<String> dateList= SliceUpDateUtil.sliceUpDateRange(bengin,end,3);
        for (int i = 0; i < dateList.size(); i++) {
            dataTimeMap.put(dateList.get(i),i);
        }
        if(list!=null &&list.size()>0){
            for (ExtBodyTemplate extBodyTemplate : list) {
                if(!hashMap.containsKey(extBodyTemplate.getDateYear())){
                    LinkedList<ExtBodyTemplate> linkList=new LinkedList<ExtBodyTemplate>();
                    linkList.add(extBodyTemplate);
                    hashMap.put(extBodyTemplate.getDateYear(),linkList);
                }else{
                    LinkedList<ExtBodyTemplate> oldlinkList=  hashMap.get(extBodyTemplate.getDateYear()) ;
                    oldlinkList.add(extBodyTemplate);
                    hashMap.put(extBodyTemplate.getDateYear(),oldlinkList);
                }
            }
            //将时间进行转换
            Set<Map.Entry<String, LinkedList<ExtBodyTemplate>>> entrySet = hashMap.entrySet();
            for (Map.Entry<String, LinkedList<ExtBodyTemplate>> stringObjectEntry : entrySet) {
                LinkedList<ExtBodyTemplate> mapList = stringObjectEntry.getValue();

                for (ExtBodyTemplate extBodyTemplate : mapList) {
                    int len = extBodyTemplate.getDateHour().length();// 取得字符串的长度
                    int index = 0;// 预定义第一个非零字符串的位置

                    char strs[] = extBodyTemplate.getDateHour().toCharArray();// 将字符串转化成字符数组
                    for (int j = 0; j < len; j++) {
                        if ('0' != strs[j]) {
                            index = j;// 找到非零字符串并跳出
                            break;
                        }
                    }
                    String dateHour = extBodyTemplate.getDateHour().substring(index, len);// 截取字符串
                    extBodyTemplate.setTimes(dataTimeMap.get(extBodyTemplate.getDateYear())*24+(Integer.parseInt(dateHour)));
                    newList.add(extBodyTemplate);
                }
            }
        }
    }
    /**
     * 根据周与病人id查询在科病人的体温图数据
     * @param map
     * @return
     */
    public List<ExtBodyTemplate> getListByWeekMouthTemplate(Map<String,Object> map){
        List<ExtBodyTemplate> list=  bodyTemperatureDao.getListByWeekMouthTemplate(map);
        List<ExtBodyTemplate> newList=new LinkedList<ExtBodyTemplate>();
        getNewList(newList,list,map);
        return newList;
    }
    /**
     * 根据周与病人id查询在科病人的体温图数据
     * @param map
     * @return
     */
    public List<ExtBodyTemplate> getListByWeekArmpitTemplate(Map<String,Object> map){
        List<ExtBodyTemplate> list=  bodyTemperatureDao.getListByWeekArmpitTemplate(map);
        List<ExtBodyTemplate> newList=new LinkedList<ExtBodyTemplate>();
        getNewList(newList,list,map);
        return newList;
    }
    /**
     * 根据时间和code查询体温单对象
     * @param map
     * @return
     */
    public BodyTemperature queryDataByTimeAndCode(Map<String,Object> map){
        return bodyTemperatureDao.queryDataByTimeAndCode(map);
    }

    /**
     * 根据时间和病人id查询体温单对象
     * @param map
     * @return
     */
    public List<ExtBodyTemplate> queryDataByTimeAndPatientId(Map<String,Object> map){
        return bodyTemperatureDao.queryDataByTimeAndPatientId(map);
    }

    /**
     * 根据当前时间和患者id删除数据
     * @param map
     */
    public int deleteByPatientIdAndNowTime(Map<String, Object> map) {

        return bodyTemperatureDao.deleteByPatientIdAndNowTime(map);
    }

    /**
     * 获取体温单所有数据
     * @param dateList
     * @param patientId
     * @param data
     */
    public void getAllList(List<String> dateList, String patientId, Map<String, Object> data,int week) {
        //获取心率和脉搏的折线
        // List<TemperatureMomentDTO>  hrAndRRList= vitalSignService.findTemperatureData(patientId,dateList);

        //List<TemperatureMomentDTO>  hrAndRRList= vitalSignService.findTemperatureHRData(patientId,dateList);
        List<TemperatureMomentDTO>  hrAndRRList= vitalSignMergeService.findTemperatureCodeData(patientId,dateList,"hr");
        data.put("hrList",hrAndRRList);
        //List<TemperatureMomentDTO>  pulseList= vitalSignService.findTemperaturePulseData(patientId,dateList);
        // data.put("pulseList",pulseList);
        //获取体温的折线
        //List<TemperatureMomentDTO>  temperatureList =vitalSignService.findTemperatureTWData(patientId,dateList);
        //List<TemperatureMomentDTO>  temperatureList= vitalSignMergeService.findTemperatureCodeData(patientId,dateList,"temperature");
        //获取所有的体温信息
        List<TemperatureMomentDTO>  temperatureList= vitalSignMergeService.findTemperatureCode(patientId,dateList,"temperature");
        data.put("temperatureList",temperatureList);
        //获取呼吸的数据  temperature
        //List<TemperatureMomentDTO>  brList =vitalSignService.findTemperatureBrData(patientId,dateList);
        // List<TemperatureMomentDTO>  brList= vitalSignService.findTemperatureCodeData(patientId,dateList,"br");
        // data.put("brList",brList);
        //获取疼痛的折线=======================
        // List<TemperatureMomentDTO>  painList= vitalSignService.findTemperatureAcheScoreData(patientId,dateList);
        //data.put("painList",painList);
        //获取血压的数据
        //List<TemperatureMomentDTO> bpList=vitalSignService.findTemperatureBloodPressureData(patientId,dateList);
        //data.put("bpList",bpList);
        //获取文字说明
        List<TemperatureMomentDTO> wordsList=vitalSignService.findTemperatureChineseStatusData(patientId,dateList);
        data.put("wordsList",wordsList);
        Map<String, Object> requestMap=new HashMap<String, Object>();
        requestMap.put("patientId",patientId);
        requestMap.put("pageNumber",week);
        List<TemperatureMomentDTO>  brList= vitalSignMergeService.findTemperatureCodeData(patientId,dateList,"br");
        Map<String, Object> map=temperatureDataService.getDataList(requestMap);
        //填充24小时的出入量
        getInOutputList(dateList,patientId,map);
        data.put("otherData", JSONObject.fromObject(map));
        data.put("brList",brList);
    }
    /**
     * 通过时间和患者id查询出入量总结的入量和出量数据
     */
    public void getInOutputList(List<String> dateList, String patientId, Map<String, Object> mapAll) {
         //将数据加1
       ArrayList<String> newList=new ArrayList<String>();
       //存放index的map
       HashMap<String,Integer> mapDays=new HashMap<String,Integer>();
        for (int i = 0; i<dateList.size(); i++) {
            //将天数累加1
            String  nextDay= getNextDay(dateList.get(i));
            newList.add(nextDay);
            mapDays.put(nextDay,i);
        }
        //查询出入量24小时的数据
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("patientId",patientId);
        map.put("list",newList);
        String[] inList = new String[ dateList.size() ];
        Arrays.fill(inList, "");
        String[] outList = new String[ dateList.size() ];
        Arrays.fill(outList, "");
        //由于可能某天没有总结，可能不是所有的数据，需要角标对应时间
        List<InOutAmount> list= inOutAmountService.getTemplateInOutData(map);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if(list!=null &&list.size()>0){
             int size=list.size();
            for (int i = 0; i<size; i++) {
                Date dataTime = list.get(i).getDataTime();
                String  day=  simpleDateFormat.format(dataTime);
                Integer day_index = mapDays.get(day);
                String outNum= list.get(i).getTotalOutNum();
                String inNum= list.get(i).getDosage();
                inList[day_index]=inNum+"";
                outList[day_index]=outNum+"";
            }
        }
        //判断填写的数据有没有值，没有值赋值出入量中的值
        String[] code3List = (String[])mapAll.get("code3");
        for (int i = 0; i<code3List.length; i++) {
            if(code3List[i]=="" || code3List[i]==null ){
                code3List[i]=inList[i];
            }
        }
        String[] code4List = (String[])mapAll.get("code4");
        for (int i = 0; i<code3List.length; i++) {
            if(code4List[i]=="" || code4List[i]==null  ){
                code4List[i]=outList[i];
            }
        }
        mapAll.put("code3",code3List);
        mapAll.put("code4",code4List);
    }
    /**
     * 计算下一天的日期
     */
    public  String   getNextDay(String  day){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date_day = null;
        try {
            date_day = simpleDateFormat.parse(day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date date_next_day = new Date(date_day.getTime() + 24 * 60 * 60 * 1000);
        String  nextDay=  simpleDateFormat.format(date_next_day);
        return nextDay;
    }
}
